<template>
    <el-container>
        <el-header>
            <h2>公司配件库存</h2>
            <el-input v-model="name" style="width: 240px" placeholder="请输入配件名称" @input="loadParts(1)" />
            <el-input v-model="supplier" style="width: 240px" placeholder="请输入配件厂商" @input="loadParts(1)" />
            <el-button type="primary" @click="dowload">导出数据</el-button>

            <el-button type="primary" @click="showAddPartDialog">添加配件</el-button>
        </el-header>

        <el-main>
            <el-row>
                <el-col :span="6">
                    <el-upload ref="uploadRef" class="upload-demo" action="#" :auto-upload="false"
                        :http-request="handleUpload">
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>

                        <el-button class="ml-3" type="success" @click="submitUpload">
                            提交到数据库
                        </el-button>

                        <template #tip>
                            <div class="el-upload__tip">
                                建议使用模板上传
                            </div>
                        </template>
                    </el-upload>
                </el-col>
            </el-row>
            <el-table :data="parts" style="width: 100%">
                <el-table-column prop="partId" label="配件ID" width="70" />
                <el-table-column prop="partName" label="配件名称" />
                <el-table-column prop="supplier" label="厂家" />
                <el-table-column prop="quantity" label="库存" width="120" />
                <el-table-column prop="price" label="价格" width="120" />
                <el-table-column prop="purchasePrice" label="进价" width="150" />
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button @click="showUpdatePartDialog(scope.row.partId)" type="danger">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row class="row-bg" justify="space-evenly">
                <el-col :span="6">
                    <el-pagination layout="prev, pager, next" :total="pageInfo.total" :page-size="pageInfo.pageSize"
                        @current-change="loadParts" />
                </el-col>
            </el-row>
        </el-main>
        <!-- START 新增窗口 -->
        <el-dialog v-model="addPartDialogVisible" title="添加配件">
            <el-form :model="newPart">
                <el-form-item label="配件名称">
                    <el-input v-model="newPart.partName"></el-input>
                </el-form-item>
                <el-form-item label="配件厂商">
                    <el-input v-model="newPart.supplier"></el-input>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input type="number" v-model="newPart.quantity"></el-input>
                </el-form-item>
                <el-form-item label="售价">
                    <el-input type="number" v-model="newPart.price"></el-input>
                </el-form-item>
                <el-form-item label="进价">
                    <el-input type="number" v-model="newPart.purchasePrice"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addPartDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addPart">提交</el-button>
            </div>
        </el-dialog>
        <!-- END 新增窗口 -->


        <!-- START 编辑窗口 -->
        <el-dialog v-model="updatePartDialogVisible" title="修改配件">
            <el-form :model="updatePart">
                <el-form-item label="配件名称">
                    <el-input v-model="updatePart.partName"></el-input>
                </el-form-item>
                <el-form-item label="配件厂商">
                    <el-input v-model="updatePart.supplier"></el-input>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input type="number" v-model="updatePart.quantity"></el-input>
                </el-form-item>
                <el-form-item label="售价">
                    <el-input type="number" v-model="updatePart.price"></el-input>
                </el-form-item>
                <el-form-item label="进价">
                    <el-input type="number" v-model="updatePart.purchasePrice"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="updatePartDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="updatePartInfo">提交</el-button>
            </div>
        </el-dialog>
        <!-- END 编辑窗口 -->
    </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import partAPi from '@/api/partApi';
import fileApi from '@/api/fileApi';

const parts = ref([]);
const pageInfo = ref({});
const addPartDialogVisible = ref(false);
const updatePartDialogVisible = ref(false);
const newPart = ref({
    partName: '',
    supplier: '',
    quantity: 0,
    price: 0,
    purchasePrice: 0,
});

const updatePart = ref({
    partName: '',
    supplier: '',
    quantity: 0,
    price: 0,
    purchasePrice: 0,
});
const name = ref('');
const supplier = ref('');

const loadParts = (page) => {
    partAPi.getAll(page, name.value, supplier.value)
        .then(resp => {
            if (resp.code === 10000) {
                pageInfo.value = resp.data;
                parts.value = resp.data.list;
            }
        });
};

const addPart = () => {
    partAPi.addInfo(newPart.value)
        .then(resp => {
            if (resp.code === 10000) {
                ElMessage.success(resp.msg);
                loadParts(pageInfo.value.pageNum);
                addPartDialogVisible.value = false;
                newPart.value = {
                    partName: '',
                    supplier: '',
                    quantity: 0,
                    price: 0,
                    purchasePrice: 0,
                }
            } else {
                ElMessage.error(resp.msg);
            }
        });
};

const updatePartInfo = () => {
    partAPi.updateInfo(updatePart.value)
        .then(resp => {
            if (resp.code === 10000) {
                ElMessage.success(resp.msg);
                loadParts(pageInfo.value.pageNum);
                updatePartDialogVisible.value = false;
            }
        });
}

// 显示修改窗口
const showUpdatePartDialog = (id) => {
    partAPi.getById(id)
        .then(resp => {
            if (resp.code === 10000) {
                updatePart.value = resp.data;
                updatePartDialogVisible.value = true;
            }
        });
}

const showAddPartDialog = () => {
    addPartDialogVisible.value = true;
};

// START excel相关内容
const uploadRef = ref()

// 上传的请求
const handleUpload = (file) => {
    let fd = new FormData();
    fd.append("file", file.file);
    fileApi.excelUpload(fd)
        .then(resp => {
            if (resp.code === 10000) {
                ElMessage.success(resp.msg);
            } else {
                ElMessage.error(resp.msg);
            }
        });
}

const submitUpload = () => {
    if (uploadRef.value != null) {
        uploadRef.value.submit();
    } else {
        ElMessage.error("请选择文件");
    }
}

// 时间戳获得时间
function format(dataString) {
    //dataString是整数，否则要parseInt转换
    var time = new Date(dataString);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var day = time.getDate();
    var hour = time.getHours();
    var minute = time.getMinutes();
    var second = time.getSeconds();
    return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + '_' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second)
}

const dowload = () => {
    fileApi.excelDowload()
        .then(res => {
            let blob = new Blob([res], { type: 'application/xlsx' })
            let url = window.URL.createObjectURL(blob)
            const link = document.createElement('a') // 创建a标签
            link.href = url
            var timestamp = Date.parse(new Date());
            var name = format(timestamp)
            link.download = `库存清单${name}.xlsx` // 重命名文件
            link.click()
            URL.revokeObjectURL(url)
        });
}
// END excel相关内容



onMounted(() => {
    loadParts(1);
});
</script>

<style scoped>
.el-container {
    background-color: #f2f2f2;
    padding: 20px;
}

.el-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #409eff;
    color: white;
    padding: 10px 20px;
    border-radius: 5px;
}

.el-main {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}
</style>